<?php 

namespace app\api\controller;
use \think\Db;
use \think\Request;
use app\api\model\ServiceClass;
use app\api\model\Service;
use app\api\model\Account;
use app\api\model\ServiceAddr;
use app\api\model\Order;

class Index extends Controller
{
	/**
	*客户端首页
	*Index/index
	*@param page //当前页
	*2017.12.16
	*BY HF
	*/
	public function index(){
		if($this->request->param('sex')){
			$map=['sex'=>$this->request->param('sex')];
		}
		if($this->request->param('age')){
			$str=$this->request->param('age');
			$ageArr=explode('~', $str);
			$map['age']=['between',[$ageArr[0],$ageArr[1]]];
		}
		if($this->request->param('height')){
			$str=$this->request->param('heigth');
			$heightArr=explode('~',$str);
			$map['height']=['between',[$heightArr[0],$heightArr[1]]];
		}
		if($this->request->param('weight')){
			$str=$this->request->param('weight');
			$weightArr=explode('~',$str);
			$map['height']=['between',[$weightArr[0],$weightArr[1]]];
		}
		$map['isdelete']=0;
		$map['audit_status']=3;//审核通过
		$map['identity']=0; //0代表技师
		$map['status']=['neq',0];
		$page=$this->request->param('page');
		$arr=Db::name('user')->where($map)->order('create_time desc')->page($page,4)->select();
		// echo Db::getLastSql();
		// exit;

		$carousel_map=[
			's.isdelete'=>0,
			'i.isdelete'=>0,
			'i.folder'=>'carousel',
		];
		$list=Db::table('tp_carousel')->alias('s')
    						   ->join('img i','s.id=i.relation_id','LEFT')
    						   ->field('s.*,i.url img_url')
    						   ->where($carousel_map)
    						   ->order('create_time desc')
    						   ->select();
    	
    	if($list){
    		foreach ($list as &$val) {
    			// $val['md_imgurl']=HTTP_HOST.'/uploads/carousel/'.imghandle($val['img_url'],'md_');
    			$val['md_imgurl']=HTTP_HOST.'/uploads/carousel/'.$val['img_url'];
    		} 
    	}
		if($arr){
			foreach ($arr as &$val) {
				$imgs=Db::name('img')->where(['isdelete'=>0,'folder'=>'headimg','relation_id'=>$val['id']])->field('url')->find();
				$val['url']=$imgs['url']?HTTP_HOST.'/uploads/headimg/'.$imgs['url']:null;
				$val['location']=get_location($val['id']);
			}
			$count=Db::name('user')->where($map)->count();		 
			$pages=ceil($count/4);  //总页数
			return ['data' => $arr,'code' => 200 , 'message' => '操作完成','page'=>$pages,'carousel'=>$list];
		}else{
			return ['code'=>400,'message'=>'暂无数据'];
		}
	}
	/**
	*客户端详情页
	*Index/detail
	*@param id  //技师ID
	*2017.12.18
	*BY HF
	*/
	public function detail(){
		$id=$this->request->param('id');
		if($id){
			Db::startTrans();
			try{
			    $arr=Db::name('user')->field('id,nickname,sex,age,status,height,weight,introduction')->find($id);
			    $headimg=Db::name('img')->where(['isdelete'=>0,'folder'=>'headimg','relation_id'=>$id])->field('url')->order('id desc')->find();
				$imgs=Db::name('img')->where(['isdelete'=>0,'folder'=>'shenghuo','relation_id'=>$id])->field('url')->select();	
			    // 提交事务
			    Db::commit();    
			} catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
			    return ['code'=>400,'message'=>'数据异常,稍候再试'];
			}
			foreach ($imgs as &$val) {
				$val['url']=HTTP_HOST.'/uploads/shenghuo/'.imghandle($val['url'],'md_');
			}
			$arr['headimg']=$headimg['url']?HTTP_HOST.'/uploads/headimg/'.imghandle($headimg['url'],'md_'):HTTP_HOST.'/uploads/headimg/moren2.jpg';
			$arr['photo']=$imgs;

			return array_merge(['code'=>200,'message'=>'正常'],$arr);
		}else{
			return ['code'=>400,'message'=>'缺少必要参数'];
		}
	}
	/**
	*客户端价目表(下单页面)
	*Index/priceList
	*@param id  技师ID
	*@param c_id  客户ID
	*2017.12.18 
	*BY HF
	*/
	public function priceList(){
		$id=$this->request->param('id');
		$c_id=$this->request->param('c_id');
		if($id && $c_id){
			$obj=new MyCenter;
			$res=$obj->price_list();
			if($res['code']==200){
				$addr=Db::name('service_addr')->where(['isdelete'=>0,'u_id'=>$c_id])->order('id desc')->find();
				if($addr){
					return array_merge(['code'=>200,'message'=>'请求成功','data'=>$res['data']],$addr);
				}else{
					return array_merge(['code'=>200,'message'=>'请求成功','data'=>$res['data']]);
				}
			}else{
				return ['code'=>400,'message'=>'暂无数据'];
			}
		}else{
			return ['code'=>400,'message'=>'缺少必要参数'];
		}
	}
	/**
	*
	*小程序 价目表
	*Index/wpriceList
	*@param id  技师ID
	*2018.01.10
	*BY HF 
	*/
	public function wpriceList(){
		$id=$this->request->param('id');
		$obj=new MyCenter;
		$res=$obj->price_list();
		if($res['code']==200){


			foreach ($res['data'] as &$val) {
				$val['description']=intercept($val['description'],15);
			}



			return ['code'=>200,'message'=>'请求成功','data'=>$res['data']];
		}else{
			return ['code'=>400,'message'=>'暂无数据'];
		}
	}



	/**
	*客户端 去结算
	*Index/settlement
	*@param c_id  客户ID   必须
	*@param s_id  技师ID   必须
	*@param item[] 数组 项目ID数组 必须
	*2017.12.22
	*BY HF
	*/
	public function settlement(){
		$param=$this->request->param();

		if(isset($param['item']) && count(json_decode($param['item']))){
			$arr=json_decode($param['item']);
			if(!$this->request->param('c_id')){
				return ['code'=>400,'message'=>'缺少必要参数'];
			}
			if(!$this->request->param('s_id')){
				return ['code'=>400,'message'=>'缺少必要参数'];
			}
			$map=[
				'i.folder'=>'service',
				'i.isdelete'=>0,
			];
			$list=Db::table('tp_service')->alias('s')
										 ->join('img i','s.id=i.relation_id','LEFT')
										 ->where($map)
										 ->where('s.id','in',$arr)
										 ->field('s.*,i.url')
										 ->order('s.create_time desc')
										 ->select();
			$tot=0;
			foreach ($list as &$val) {
				$val['url']=HTTP_HOST.'/uploads/service/'.imghandle($val['url'],'sm_');
				$val['description_sub']=intercept($val['description'],16);
				$tot+=$val['price'];
			}
			$userinfo=Db::table('tp_user')->alias('u')
										  ->join('service_addr sa','u.id=sa.u_id','LEFT')
										  ->where(['sa.isdelete'=>0])
										  ->field('u.name,u.tel,sa.*')
										  ->find($this->request->param('c_id'));
			$res=['item'=>$list,'service_addr'=>$userinfo,'rest'=>['s_id'=>$this->request->param('s_id'),'c_id'=>$this->request->param('c_id'),'tot'=>$tot]];
			return ['code'=>200,'message'=>'请求成功','data'=>$res];
		}else{
			return ['code'=>400,'message'=>'您还没有选择服务项目，不能结算'];
		}
	}

	/**
	*客户端 提交订单
	*Index/create_order
	*@param c_id    //客户ID
	*@param s_id  //技师ID
	*@param ids Array 服务项目ID集合如：[22,21,20,19]
	*@param sa_id  //服务地址ID
	*@param appointment 预约时间 格式：2017-09-05 09:01
	*@param price 总价钱
	*@param remark 备注
	*2017.12.23
	*BY HF
	*/
	public function create_order(){

		$param=$this->request->param();

		$param['ids']=str_replace('&quot;','',$param['ids']); 


		$ids=json_decode($param['ids']);
		$sa_id=$param['sa_id'];
		

		$c_id=$param['c_id'];
		$s_id=$param['s_id'];
		$s_user=Db::name('user')->field('name,nickname,tel,status')->find($s_id);
		$c_user=Db::name('user')->field('name,nickname,tel')->find($c_id);
		$service_addr=Db::name('service_addr')->find($sa_id);


		$service_ids='';
		$service_name='';
		$service_price='';
		$service_time='';


		for ($i=0; $i <count($ids) ; $i++) { 
			$serviceList=Db::name('service')->field('name,price,time')->find($ids[$i]);
			$service_ids.=$ids[$i].'|';
			$service_name.=$serviceList['name'].'|';
			$service_price.=$serviceList['price'].'|';
			$service_time.=$serviceList['time'].'|';
		}
		// echo'<pre>'; 
		// print_r($s_user); 
		// echo'</pre>'; 

		// echo'<pre>'; 
		// print_r($c_user); 
		// echo'</pre>'; 

		// echo'<pre>'; 
		// print_r($param); 
		// echo'</pre>'; 

		if($s_user['status']==1){
			$order_status=3; //订单是：已接单未服务状态
		}else{
			$order_status=1; //订单是：预约单状态
		}
		$data=[
			'order_num'=>date('YmdHis').$c_id.substr(time(),strlen(time())-4,4),
			's_id'=>$s_id,
			's_tel'=>$s_user['tel'],
			's_name'=>$s_user['name'],
			's_nickname'=>$s_user['nickname'],
			'c_id'=>$c_id,
			'c_tel'=>$c_user['tel'],
			'c_name'=>$c_user['name'],
			'c_nickname'=>$c_user['nickname'],
			'service_ids'=>substr($service_ids,0,strlen($service_ids)-1),
			'service_name'=>substr($service_name,0,strlen($service_name)-1),
			'service_price'=>substr($service_price,0,strlen($service_price)-1),
			'service_time'=>substr($service_time,0,strlen($service_time)-1),
			'service_addr_id'=>$sa_id,
			'service_addr_name'=>$service_addr['name'],
			'service_addr_tel'=>$service_addr['tel'],
			'service_addr'=>$service_addr['city'].$service_addr['area'].$service_addr['street'].$service_addr['addr'],
			'appointment'=>$param['appointment'],
			'price'=>$param['price'],
			'pay_status'=>0,
			'remark'=>$param['remark'],
			'order_status'=>$order_status, //需要根据技师状态决定
			'create_time'=>date('Y-m-d H:i:s'),
		];
		$id=Db::name('order')->insertGetId($data);

		if($id){
			if($order_status==3){
				//需要支付	
				$data=['zhifu'=>1,'orderId'=>$id];
				return array_merge(['code'=>200,'message'=>'请去支付'],$data);
			}else{
				//预约单不需要支付
				$data=['zhifu'=>0,'orderId'=>$id];
				return array_merge(['code'=>200,'message'=>'不需要支付可直接跳转到预约单'],$data);
			}
		}else{
			return ['code'=>400,'message'=>'订单提交失败，请稍后再试'];
		}
	}


	/**
	*统一下单接口
	*Index/xiadan
	*@param id 订单ID
	*2017.12.23
	*BY HF
	*/
	public function xiadan(){
		if($this->request->param('id')){
			$order=Db::name('order')->field('order_num,price')->find($this->request->parma('id'));
			$order_num=$order['num'];
			$order_price=$order['price']*100; //总金额  $order['price']单位是元
			$url='https://api.mch.weixin.qq.com/pay/unifiedorder';
			$type='post';
			$res='json';
			//准备参数
			$appid = config('appid');  //appid必须  字符串
			$mch_id =config('mch_id');  //商户号  字符串
			$nonce_str=make_rand(30); //随机字符串(使用随机函数生成)   字符串
			$body='货源宝-订单金额';      //例如：天天爱消除-游戏充值。字符串
			$spbill_create_ip=Request::instance()->ip();        //用户实际ip  字符串
			$notify_url=config('notify_url');              //接收微信支付异步通知回调地址
			$trade_type='APP';           //支付类型

			$sign=make_sign($appid,$body,$mch_id,$nonce_str,$notify_url,$order_num,$spbill_create_ip,$order_price,$trade_type);                     //签名   字符串
			$arr="
			      <xml>
			         <appid>{$appid}</appid>
			         <body>{$body}</body>
			         <mch_id>{$mch_id}</mch_id>
			         <nonce_str>{$nonce_str}</nonce_str>
			         <notify_url>{$notify_url}</notify_url>
			         <out_trade_no>{$order_num}</out_trade_no>
			         <spbill_create_ip>{$spbill_create_ip}</spbill_create_ip>
			         <total_fee>{$order_price}</total_fee>
			         <trade_type>{$trade_type}</trade_type>
			         <sign>{$sign}</sign>
			      </xml>
			";
			//1.初始化curl
			$ch = curl_init();
			//2.设置curl的参数
			curl_setopt($ch, CURLOPT_URL, $url);

			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			if($type == 'post'){
			      curl_setopt($ch,CURLOPT_POST,1);
			      curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
			}
			//3.执行请求
			$output = curl_exec($ch);
			//4.关闭
			curl_close($ch);
			/*
			  返回值信息
			  <xml><return_code><![CDATA[SUCCESS]]></return_code>
			  <return_msg><![CDATA[OK]]></return_msg>
			  <appid><![CDATA[wxa6bd9c6fec8d10bc]]></appid>
			  <mch_id><![CDATA[1484041422]]></mch_id>
			  <nonce_str><![CDATA[xghxj1JN4k28lp4b]]></nonce_str>
			  <sign><![CDATA[F2B3AF912FD01442AB3EEE6E57A6EC31]]></sign>
			  <result_code><![CDATA[SUCCESS]]></result_code>
			  <prepay_id><![CDATA[wx20170916172225e972558ad90510359662]]></prepay_id>
			  <trade_type><![CDATA[APP]]></trade_type>
			  </xml>
			*/
			$brr=json_decode(json_encode(simplexml_load_string($output, 'SimpleXMLElement', LIBXML_NOCDATA)),true);

			/*
			返回信息转化为数组
			  Array
			  (
			      [return_code] => SUCCESS
			      [return_msg] => OK
			      [appid] => wxa6bd9c6fec8d10bc
			      [mch_id] => 1484041422
			      [nonce_str] => DiOJxzG32d1rFZCA
			      [sign] => 5CAF40451792C6D0CF0FB1F05C5A63EA
			      [result_code] => SUCCESS
			      [prepay_id] => wx2017091617310579e1dfd8f00917846722
			      [trade_type] => APP
			  )
			*/
			if($brr['return_code']=='SUCCESS'){
			    //生成签名信息
			    //appid，partnerid，prepayid，noncestr，timestamp，package。
			    $noncestr=make_rand(30);  //随机码
			    $package='Sign=WXPay';
			    $partnerid = $mch_id ;//商户号
			    $prepayid=$brr['prepay_id'];  //交易会话ID
			    $timestamp=time(); //时间戳
			    //生成签名
			    $stringA="appid={$appid}&noncestr={$noncestr}&package={$package}&partnerid={$partnerid}&prepayid={$prepayid}&timestamp={$timestamp}"; 
			    $stringSignTemp=$stringA."&key=wwwcnhttxhuoyunbao0123456789Apik"; //注：key为商户平台设置的密钥key 
			    $sign=strtoupper(md5($stringSignTemp)); //注：MD5签名方式
			    return ['code'=>200,'message'=>'请求成功','data'=>['appid'=>$appid,'noncestr'=>$noncestr,'package'=>$package,'partnerid'=>$partnerid,'prepayid'=>$prepayid,'timestamp'=>$timestamp,'sign'=>$sign]];
			}else{
			    return ['code'=>400,'message'=>'请求微信支付失败,请稍后再试','data'=>0];
			}
		}else{
			return ['code'=>400,'message'=>'缺少必要的参数ID'];
		}
	}
	/**
	*支付完成后接收微信异步通知的方法
	*Index/notify_url
	*2017.12.23
	*BY HF
	*/
    public function notify_url(){
        $xml=file_get_contents("php://input");
          /*$xml="
                <xml>
                	<appid><![CDATA[wxa6bd9c6fec8d10bc]]></appid>
					<bank_type><![CDATA[CITIC_CREDIT]]></bank_type>
					<cash_fee><![CDATA[1]]></cash_fee>
					<fee_type><![CDATA[CNY]]></fee_type>
					<is_subscribe><![CDATA[N]]></is_subscribe>
					<mch_id><![CDATA[1484041422]]></mch_id>
					<nonce_str><![CDATA[adrvwyzABCDEIJLMNOPRUY01245678]]></nonce_str>
					<openid><![CDATA[o8DQb1u-HJ7JU3GnoS0_-KPUD6oY]]></openid>
					<out_trade_no><![CDATA[2143]]></out_trade_no>
					<result_code><![CDATA[SUCCESS]]></result_code>
					<return_code><![CDATA[SUCCESS]]></return_code>
					<sign><![CDATA[5A398382F4C5064586288460B0ECB699]]></sign>
					<time_end><![CDATA[20170922144853]]></time_end>
					<total_fee>1</total_fee>
					<trade_type><![CDATA[APP]]></trade_type>
					<transaction_id><![CDATA[4200000004201709223572345964]]></transaction_id>
				</xml>
           ";*/
        //讲返回数据写入日志文件中
        file_put_contents('./apipaylog/'.date('YmdHis').'.log',$xml);
        libxml_disable_entity_loader(true);
        // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml=json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
		/*
		转化成数组后
		array(16) {
			["appid"] => string(18) "wxa6bd9c6fec8d10bc"      //appid
			["bank_type"] => string(12) "CITIC_CREDIT"        //银行卡类型
			["cash_fee"] => string(1) "1"                     //支付金额为1分
			["fee_type"] => string(3) "CNY"                   //货币种类    人民币
			["is_subscribe"] => string(1) "N"                 //是否关注公众号  Y | N
			["mch_id"] => string(10) "1484041422"             //商户号
			["nonce_str"] => string(30) "abemqrsuvwzBDEFGKNOPSUY1356789"   //随机码
			["openid"] => string(28) "o8DQb1u-HJ7JU3GnoS0_-KPUD6oY"   //用户在商户appid下的唯一标识
			["out_trade_no"] => string(4) "2027"                 //订单id2027
			["result_code"] => string(7) "SUCCESS"              //结果码
			["return_code"] => string(7) "SUCCESS"              //返回码
			["sign"] => string(32) "582FA88414A32A6867ECF87FA6015866"  //签名
			["time_end"] => string(14) "20170918163456"             //支付完成时间
			["total_fee"] => string(1) "1"                     //总金额
			["trade_type"] => string(3) "APP"                  //支付方式
			["transaction_id"] => string(28) "4006692001201709182834582482"  //微信支付订单号
		}
		*/

		$res="
		  <xml> 
		    <return_code><![CDATA[SUCCESS]]></return_code>
		    <return_msg><![CDATA[OK]]></return_msg>
		  </xml> 
		";
		$error_res="
		  <xml> 
		    <return_code><![CDATA[FAIL]]></return_code>
		    <return_msg><![CDATA[OK]]></return_msg>
		  </xml> 
		";
		$appid=$xml['appid'];
		$bank_type=$xml['bank_type'];
		$cash_fee=$xml['cash_fee'];
		$fee_type=$xml['fee_type'];
		$is_subscribe=$xml['is_subscribe'];
		$mch_id=$xml['mch_id'];
		$nonce_str=$xml['nonce_str'];
		$openid=$xml['openid'];
		$out_trade_no=$xml['out_trade_no'];
		$result_code=$xml['result_code'];
		$return_code=$xml['return_code'];
		$time_end=$xml['time_end'];
		$total_fee=$xml['total_fee'];
		$trade_type=$xml['trade_type'];
		$transaction_id=$xml['transaction_id'];
		//做签名验证
		//生成签名信息
		$stringA="appid={$appid}&bank_type={$bank_type}&cash_fee={$cash_fee}&fee_type={$fee_type}&is_subscribe={$is_subscribe}&mch_id={$mch_id}&nonce_str={$nonce_str}&openid={$openid}&out_trade_no={$out_trade_no}&result_code={$result_code}&return_code={$return_code}&time_end={$time_end}&total_fee={$total_fee}&trade_type={$trade_type}&transaction_id={$transaction_id}"; 
		$stringSignTemp=$stringA."&key=wwwcnhttxhuoyunbao0123456789Apik"; //注：key为商户平台设置的密钥key 
		$sign=strtoupper(md5($stringSignTemp)); //注：MD5签名方式

        if($sign==$xml['sign']){
            //签名验证通过
            if($xml['result_code']=='SUCCESS'){
                //支付成功
                //1.检查数据库中的订单支付状态,若为支付状态pay_status =0 则修改，为1则表示已支付
            	$orderList=Db::name('order')->field('pay_status')->where(['order_num'=>$out_trade_no])->find();
            	if($orderList['pay_status']==1){
            		return $res;
            	}else{
            		if(Db::name('order')->where(['order_num'=>$out_trade_no])->update(['pay_status'=>1])){
            			//发送短信通知技师有人下单，请及时联系
            			$Order=new Order;
            			$return=$Order->get_option($out_trade_no);
            			sms($return->s_tel,'SMS_126359460','贵妃养生','order',$return->order_num);
            			return $res;
            		}else{
            			return $error_res;
            		}
            	}
              }else{
                  //支付失败
                  return $error_res;
              }
          }else{
            //签名验证失败
                return $error_res;
          }
    }
    /**
    *获得单个用户的位置
    *Index/getLocation
    *@param id 用户ID
    *2018.01.08
    *BY HF
    */
    public function getLocation(){
    	$id=$this->request->param('id');
    	$redis = new \redis();
		$redis->connect('127.0.0.1',6379);
		$location=$redis->get($id);
		$headimg=Db::name('img')->where(['relation_id'=>$id,'isdelete'=>0,'folder'=>'headimg'])->find();
		$headimg=$headimg?HTTP_HOST.'/uploads/headimg/'.imghandle($headimg['url'],'sm_'):HTTP_HOST.'/uploads/headimg/moren2.jpg';
		if($location){
			return ['code'=>200,'message'=>'获取成功','location'=>$location,'headimg'=>$headimg];
		}else{
			return ['code'=>400,'message'=>'暂无位置信息'];
		}
    }
	/**
	*客户端或者技师端
	* 查看位置
	*Index/location
	*@param jishi_id   技师ID
	*@param kehu_id 客户ID
	*@param j_location  技师坐标
	*@param k_location  客户坐标
	*2017.12.19 
	*BY HF
	*/
	public function location(){
		$jishi_id=$this->request->param('jishi_id');
		$kehu_id=$this->request->param('kehu_id');
		if($jishi_id && $kehu_id){
			$redis = new \redis();
			$redis->connect('127.0.0.1',6379);
			$j_location=$redis->get($jishi_id);
			$k_location=$redis->get($kehu_id);
			if($j_location && $k_location){
				return ['code'=>200,'message'=>'获取地址成功','data'=>['j_location'=>$j_location,'k_location'=>$k_location]];
			}elseif($j_location && !$k_location){
				return ['code'=>400,'message'=>'无法获取客户地址','data'=>['j_location'=>$j_location,'k_location'=>null]];
			}elseif(!$j_location && $k_location){
				return ['code'=>400,'message'=>'无法获取技师地址','data'=>['j_location'=>null,'k_location'=>$k_location]];
			}else{
				return ['code'=>400,'message'=>'无法获取地址','data'=>['j_location'=>null,'k_location'=>null]];
			}
		}else{
			return ['code'=>400,'message'=>'缺少必要参数'];
		}
	}
	/**
	*客户端或者技师端
	*设置地址
	*Index/setLocation
	*@param id 用户ID
	*@param location  用户坐标
	*2017.12.19
	*BY HF 
	*/
	public function setLocation(){
		$id=$this->request->param('id');
		$location=$this->request->param('location');
		if($id && $location){
			$redis = new \redis();
			$redis->connect('127.0.0.1',6379);
			$redis->set($id,$location);
			return ['code'=>200,'message'=>'设置成功'];
		}else{
			return ['code'=>400,'message'=>'缺少必要参数'];
		}
	}
	/**
	*客户端 确认到达指令|确认完成指令|拒绝订单指令
	*Index/change_status
	*@param id 订单ID  必须
	*@param status  订单状态 必须   1预约单2拒绝单3已接单未服务4已接单服务中5已完成6预约单已确认
	*2017.12.25
	*BY HF 
	*/
	public function change_status(){
		$param=$this->request->param();
		if($param){
			$id=$param['id'];
			$status=$param['status'];
			if(Db::name('order')->update(['id'=>$id,'order_status'=>$status])){
				if($status==5){
					//已完成，给技师计算收益占70%

					// 收益计算
					//1.账户变化
					
					$AccountModel=new Account;
					$AccountModel->income_assign($id);
					//2.收益记录


					
				}
				return ['code'=>200,'message'=>'请求成功'];
			}else{
				return ['code'=>400,'message'=>'您已确认过了，不需要重复确认了'];
			}
		}else{
			return ['code'=>400,'message'=>'缺少必要参数'];
		}
	}
	/**
	*客户端 首页 轮播图
	*Index/carousel
	*2017.12.25
	*BY HF
	*/
	public function carousel(){
		$map=[
			's.isdelete'=>0,
			'i.isdelete'=>0,
			'i.folder'=>'carousel',
		];
		$list=Db::table('tp_carousel')->alias('s')
    						   ->join('img i','s.id=i.relation_id','LEFT')
    						   ->field('s.*,i.url img_url')
    						   ->where($map)
    						   ->order('create_time desc')
    						   ->select();
    	
    	if($list){
    		foreach ($list as &$val) {
    			$val['md_imgurl']=HTTP_HOST.'/uploads/carousel/'.imghandle($val['img_url'],'md_');
    			$val['img_url']=HTTP_HOST.'/uploads/carousel/'.$val['img_url'];
    		} 
    		return ['code'=>200,'message'=>'请求成功','data'=>$list];
    	}else{
    		return ['code'=>400,'message'=>'暂无数据'];
    	}	        
	}
    /** 
     * 计算两点之间距离 
     * @param start 
     * @param end 
     * @return 米 
     */  
    public function getDistance(){  
    	$start=['latitude'=>39.95676,'longitude'=>116.401394]; //39.95676, 116.401394
    	$end=['latitude'=>36.63014,'longitude'=>114.499574]; //36.63014,114.499574
        $lat1 = (M_PI/180)*$start['latitude'];  
        $lat2 = (M_PI/180)*$end['latitude'];  
          
        $lon1 = (M_PI/180)*$start['longitude'];  
        $lon2 = (M_PI/180)*$end['longitude'];  
          
//      double Lat1r = (Math.PI/180)*(gp1.getLatitudeE6()/1E6);  
//      double Lat2r = (Math.PI/180)*(gp2.getLatitudeE6()/1E6);  
//      double Lon1r = (Math.PI/180)*(gp1.getLongitudeE6()/1E6);  
//      double Lon2r = (Math.PI/180)*(gp2.getLongitudeE6()/1E6);  
          
        //地球半径  
        $R = 6371;  
          
        //两点间距离 km，如果想要米的话，结果*1000就可以了  
        $d = acos(sin($lat1)*sin($lat2)+cos($lat1)*cos($lat2)*cos($lon2-$lon1))*$R;  
          
        return $d*1000;  
    } 

    /**
    * 客户端服务项目分类
    * @param 无
    * @return 见手册
    * 2018.03.01
    * BY HF 
    */
    public function getServiceClass(){
    	$obj=new ServiceClass;
    	$return=$obj->getClass();
    	if($return){
    		foreach ($return as &$val) {
    			$val['imgUrl']=HTTP_HOST.'/uploads/service_class/'.imghandle($val['url'],'sm_');
    		}
	    	return ['code'=>200,'message'=>'成功','data'=>$return];
    	}else{
	    	return ['code'=>400,'message'=>'失败'];
    	}
    }

    /**
    * 客户端分类下的具体项目
    * @param string 格式:[12,13,14]   ["22","21","20","19","18"]
    * @param c_id 客户ID
    * @return
    * 2018.03.02
    * BY HF
    */
    public function getService(){
    	$param=$this->request->param('ids');
    	$c_id=$this->request->param('c_id');
    	$arr=str_replace('&quot;','',$param); 
		$param=json_decode($arr);    	        
    	if($param){
    		$obj=new Service;
    		$return =$obj->get_service($param);
    		if($return){
    			foreach ($return as &$val) {
    				$val['imgUrl']=HTTP_HOST.'/uploads/service/'.imghandle($val['url'],'sm_');
    			}
    			$ServiceAddr=new ServiceAddr;
    			$addr=$ServiceAddr->getAddr($c_id);

    			if($addr){
    				$addr=$addr->toArray();
    			}else{
    				$addr=[];
    			}

	    		return array_merge(['code'=>200,'message'=>'成功','data'=>$return],$addr);
    		}
    		return ['code'=>400,'message'=>'暂无数据'];
    	}else{
	    	return ['code'=>400,'message'=>'参数出错'];
    	}
    }

    /**
    * 单个项目详情
    * @param id 项目ID
    * 2018.03.02
    * BY HF 
    */
    public function getDetail(){
    	if($this->request->param('id')){
    		$obj=new Service;
    		$return =$obj->get_service_detail($this->request->param('id'));
    		if($return){
    			$return['imgurl']=HTTP_HOST.'/uploads/service/'.imghandle($return['url'],'sm_');
	    		return array_merge(['code'=>200,'message'=>'成功'],$return);
    		}else{
	    		return ['code'=>400,'message'=>'暂无数据'];
    		}
    	}else{
	    	return ['code'=>400,'message'=>'缺少必要的参数ID'];
    	}
    }
    /**
    * 订单整理
    * 超过24小时未支付的订单，数据库将自动清除订单记录
    */

    public function order_clear(){
    	$Order=new Order;
    	$res=$Order->clear_order_option();
    	return ['code'=>200,'message'=>'清理成功'];
    }

    /**
    * 短信测试
    * 
    */
    public function send_sms(){
    	// //模板code  SMS_126755008
    	// $tel='15034426976';
    	// $tCode='SMS_126359460';
    	// // $tCode='SMS_126359460';
    	// $orderNum='201803081234';
    	// $sign='贵妃养生';
    	// // sms($tel,$tCode,$sign,$type,$orderNum=0)
    	// $res=sms($tel,$tCode,$sign,'order',$orderNum);
    	// // echo'<pre>'; 
    	// // print_r($res); 
    	// // echo'</pre>'; 
    	// var_dump($code);
    	$Order =new Order;
    	$res=$Order->get_option(2);


    	echo'<pre>'; 
    	print_r($res); 
    	echo'</pre>'; 
    	        
    }



}